<script setup lang="ts">
import {ref, reactive} from 'vue'
import ajax from '@/axios'
import router from "@/router";
import {ElMessage, type FormInstance, type FormRules} from 'element-plus'
import type {RuleForm} from '@/types'

const ruleForm = ref<RuleForm>({
  adminname: '',
  password: '',
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
  adminname: [
    {required: true, message: '请输入用户名！', trigger: 'blur'},
    {min: 3, max: 5, message: '用户名长度为3至5位', trigger: 'blur'},
  ],
  password: [ // 密码字母开头 6-18 至少含有一位数字
    {required: true, message: '请输入密码！', trigger: 'blur'},
    {pattern: /(?=.*\d)\w{5,17}$/, message: '密码错误！密码 6-18 至少含有一位数字', trigger: 'blur'},
  ]
})

function login(adminname: string, password: string) {
  console.log(adminname, password)
  ajax({
    url: '/admin/admin/login',
    method: 'post',
    data: {
      adminname,
      password,
    }
  }).then(r => {
    console.log(alert)
    console.log(r.data);
    if (r.data.code === '200') {
      ElMessage({
        message: '登录成功！',
        type: 'success',
        plain: true,
      })
      localStorage.setItem('adminToken', r.data.data.token);
      router.push('/')
    } else {
      ElMessage({
        message: '登录失败！',
        type: 'success',
        plain: true,
      })
    }
  })
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      login(ruleForm.value.adminname, ruleForm.value.password)
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<template>
  <div class="loginBox">
    <el-card style="max-width: 480px; padding: 40px">
      <h2>Login</h2>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="用户名" prop="adminname">
          <el-input v-model="ruleForm.adminname"/>
        </el-form-item>
        <el-form-item label="密&emsp;码" prop="password">
          <el-input v-model="ruleForm.password"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            登录
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">注册</el-button>
        </el-form-item>
      </el-form>

    </el-card>
  </div>
</template>

<style scoped lang="scss">
.loginBox {
  width: max-content;
  margin: 0 auto 100px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}

.list-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}
</style>
